// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { _decorator, Component, EventKeyboard, macro, systemEvent, Vec3, SystemEventType, log, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Body')
export default class Body extends Component {

    @property
    private maxMoveSpeed: number = 0;
    @property
    private acceleration: number = 0;
    private accLeft: boolean = false;
    private accRight: boolean = false;
    private xSpeed: number = 0;
    private _curPos: Vec3 = new Vec3(0,0,0);
    private _dtPos: Vec3 = new Vec3();

    @property(Node)
    private player: Node = null!;


    onKeyDown(event: EventKeyboard) {
        switch (event.keyCode) {
            case macro.KEY.a:
                this.accLeft = true;
                break;
            case macro.KEY.d:
                this.accRight = true;
                break;
        }
    }
    onKeyUp(event: EventKeyboard) {
        switch (event.keyCode) {
            case macro.KEY.a:
                this.accLeft = false;
                break;
            case macro.KEY.d:
                this.accRight = false;
                break;
        }
    }

    start(){
        this.node.setPosition(this._curPos);
    }


    onLoad(){
        systemEvent.on(SystemEventType.KEY_DOWN, this.onKeyDown, this);
        systemEvent.on(SystemEventType.KEY_UP, this.onKeyUp, this);
    }

    update(dt: number) {
        if (this.accLeft) {
            this.xSpeed -= this.acceleration * dt;
        } else if (this.accRight) {
            this.xSpeed += this.acceleration * dt;
        }
        if (Math.abs(this.xSpeed) > this.maxMoveSpeed) {
            this.xSpeed = this.maxMoveSpeed * this.xSpeed / Math.abs(this.xSpeed);
        }
        this.node.getPosition(this._curPos);
        this._dtPos.x = this.xSpeed * dt;
        Vec3.add(this._curPos, this._curPos, this._dtPos);
        this.node.setPosition(this._curPos);
    }
}
